package top.carrotguo.weibo.ui.home;

import android.Manifest;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.SpannableString;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;

import com.bumptech.glide.Glide;
import com.sina.weibo.sdk.auth.AccessTokenKeeper;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;

import java.util.ArrayList;
import java.util.List;
import java.util.logging.Logger;

import butterknife.BindView;
import butterknife.OnClick;
import retrofit2.http.PUT;
import top.carrotguo.weibo.R;
import top.carrotguo.weibo.adapter.CommentPhotoAdapter;
import top.carrotguo.weibo.adapter.EmojiAdapter;
import top.carrotguo.weibo.adapter.EmojiPagerAdapter;
import top.carrotguo.weibo.contract.SendCommentContract;
import top.carrotguo.weibo.presenter.SendCommentPresenter;
import top.carrotguo.weibo.retrofit.callback.ErrorInfo;
import top.carrotguo.weibo.ui.base.MVPBaseActivity;
import top.carrotguo.weibo.utils.EmojiUtils;
import top.carrotguo.weibo.utils.StringUtils;
import top.carrotguo.weibo.utils.TitlebarBuilder;
import top.carrotguo.weibo.utils.ToastUtils;
import top.carrotguo.weibo.utils.UIUtils;
import top.carrotguo.weibo.widget.WrapHeightGridView;

public class CommentActivity extends MVPBaseActivity<SendCommentContract.View,SendCommentPresenter>
    implements SendCommentContract.View,AdapterView.OnItemClickListener {

    @BindView(R.id.et_content)
    EditText etContent;
    @BindView(R.id.wv_photo_container)
    GridView wrPhoto;
    @BindView(R.id.ll_emoji)
    LinearLayout llEmoji;
    @BindView(R.id.vp_emoji)
    ViewPager vpEmoji;
    @BindView(R.id.iv_emoji)
    ImageView ivEmoji;


    public static final int RESULT_SEND = 1;
    public static final String ID = "ID";
    public static final String SEND_SUCCESSED = "SEND_SUCCESSED";
    //选择图片请求码
    public static final int REQUEST_CODE_CHOOSE = 2;
    //添加更多图片请求码
    public static final int REQUEST_CODE_ADD_MORE = 3;
    //权限请求码
    private static final int REQUEST_CODE = 1;
    //即将申请权限的名字
    String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE
            ,Manifest.permission.READ_EXTERNAL_STORAGE};
    //选择的图片URI
    private List<Uri> mSelected = new ArrayList<>();
    //创建一个List，用于存放哪些权限未获取
    List<String> unGetPermissions = new ArrayList<>();
    private String id;
    private CommentPhotoAdapter mPhotoAdapter;


    @Override
    protected void initView() {
        super.initView();
        new TitlebarBuilder(mContext)
                .setCenterTitle("发评论")
                .setLeftText("取消")
                .setRightText("发送")
                .setLeftTextClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        clickCancel();
                    }
                })
                .setRightTextClick(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        clickSend();
                    }
                });

    }

    @Override
    public SendCommentPresenter createPresenter() {
        return new SendCommentPresenter();
    }

    @Override
    public int provideContentViewId() {
        return R.layout.activity_comment;
    }

    @Override
    public Bundle getBundleExtras(Bundle bundle) {
        id = bundle.getString(ID);
        //id = "4306265746876624";
        return null;
    }



    private void clickCancel(){
        //关闭当前页面，不需要返回码
        finish();
    }

    private void clickSend(){
        mPresenter.sendComment(AccessTokenKeeper.readAccessToken(mContext),id);
    }

    @Override
    public void showSending() {
        showLoading("正在发表中");
    }

    @Override
    public void hideSending() {
        hideLoading();
    }

    @Override
    public String getTextContent() {
        return etContent.getText().toString();
    }

    @Override
    public void showNoSendEmpty() {
        showToast("评论内容不能为空");
    }

    @Override
    public void showSendSuccess() {
        showToast("评论成功！");
        //等待发送结束后才推出(这段代码要放到网络请求结束后)
        Intent intent = new Intent();
        intent.putExtra(SEND_SUCCESSED,true);
        setResult(RESULT_SEND,intent);
        finish();
    }

    @Override
    public void showSendError(ErrorInfo errorInfo) {
        showToast(errorInfo.getErrorMsg());
    }

    @OnClick(R.id.iv_image)
    public void clickImage(){
        //查看是否有申请权限
        checkPermissions();
    }

    private void checkPermissions(){
        unGetPermissions.clear();
        //遍历需要申请的权限
        for (int i=0; i<permissions.length; i++) {
            if (ContextCompat.checkSelfPermission(this,permissions[i])!=PackageManager.PERMISSION_GRANTED) {
                //该权限未获取，添加到列表
                unGetPermissions.add(permissions[i]);
            }
        }
        //动态申请权限
        if(unGetPermissions.size()>0){
            ActivityCompat.requestPermissions(this,permissions,REQUEST_CODE);
            return;
        }
        //权限本来已经申请，可以做接下来的事情
        //选取图片
        choosePhoto(REQUEST_CODE_CHOOSE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        for (int i=0; i<grantResults.length; i++) {
            if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
                //有权限未通过
                showToast("请先申请权限");
                return;
            }
        }
        //选取图片
        choosePhoto(REQUEST_CODE_CHOOSE);
    }

    private void choosePhoto(int code){
        Matisse.from(CommentActivity.this)
                .choose(MimeType.ofAll(), false)
                .theme(R.style.Matisse_Zhihu)
                .countable(true)
                .maxSelectable(9-mSelected.size())
                .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
                .thumbnailScale(0.85f)
                .imageEngine(new GlideEngine())
                .forResult(code);
    }

    private void showPhoto(){
        mPhotoAdapter = new CommentPhotoAdapter(mContext,mSelected);
        wrPhoto.setAdapter(mPhotoAdapter);
        //移除图片监听
        mPhotoAdapter.setRemoveListener(new CommentPhotoAdapter.RemoveListener() {
            @Override
            public void onRemoveClickListener(int position) {
                mSelected.remove(position);
                mPhotoAdapter.notifyDataSetChanged();
            }
        });
        //添加图片监听
        mPhotoAdapter.setAddListener(new CommentPhotoAdapter.AddListener() {
            @Override
            public void onAddClickListener() {
                choosePhoto(REQUEST_CODE_ADD_MORE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
            //先清空之前选择的图片
            mSelected.clear();
            //获取选取图片的uri
            mSelected.addAll(Matisse.obtainResult(data));
            showPhoto();
        } else if (requestCode == REQUEST_CODE_ADD_MORE && resultCode == RESULT_OK) {
            mSelected.addAll(Matisse.obtainResult(data));
            mPhotoAdapter.notifyDataSetChanged();
        }
    }

    @OnClick({R.id.rb_recent,R.id.rb_noraml,R.id.rb_duck,R.id.rb_num})
    public void selectEmoji(RadioButton radioButton){
        radioButton.setChecked(true);
        switch (radioButton.getId()) {
            case R.id.rb_recent:{

                break;
            }
            case R.id.rb_noraml:{

                break;
            }
            case R.id.rb_duck:{

                break;
            }
            case R.id.rb_num:{

                break;
            }
        }
    }

    @OnClick(R.id.iv_emoji)
    public void showEmoji(View view){
        if (llEmoji.getVisibility()==View.VISIBLE) {
            //设置为不可见，并且图标改为表情
            llEmoji.setVisibility(View.GONE);
            ivEmoji.setBackgroundResource(R.drawable.selector_tool_emoji);
        } else {
            ivEmoji.setBackgroundResource(R.drawable.selector_keyboard);
            //表情面板设置可见
            llEmoji.setVisibility(View.VISIBLE);
            //计算每个表情的大小和gridview的大小
            int width = UIUtils.getScreenWidth();
            int itemWidth = (width - UIUtils.dip2px(8)*8)/7;
            int gvHeight = itemWidth*3+UIUtils.dip2px(8)*4;
            List<String> curEmojiNames = new ArrayList<>();
            List<GridView> gridViews = new ArrayList<>();
            //遍历所有表情,根据表情个数创建每一页表情
            for (String name : EmojiUtils.getNames()) {
                curEmojiNames.add(name);
                if (curEmojiNames.size() == 20) {
                    //凑够20个表情+一个回退即可作为一个gridview页面
                    GridView gridView  = createGridView(UIUtils.dip2px(8),width,itemWidth,gvHeight,curEmojiNames);
                    //将当前gridView添加到list中
                    gridViews.add(gridView);
                    //新建一页
                    curEmojiNames = new ArrayList<>();
                }
            }
            //最后一页表情
            if (curEmojiNames.size()>0) {
                GridView gridView = createGridView(UIUtils.dip2px(8),width,itemWidth,gvHeight,curEmojiNames);
                gridViews.add(gridView);
            }

            //将gridview加入viewpager
            EmojiPagerAdapter pagerAdapter = new EmojiPagerAdapter(gridViews);
            vpEmoji.setAdapter(pagerAdapter);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(width,gvHeight);
            vpEmoji.setLayoutParams(params);
        }
    }

    private GridView createGridView(int padding,int width,int itemWidth,int height,List<String> emojiNames){
        GridView gridView = new GridView(mContext);
        ViewPager.LayoutParams params = new ViewPager.LayoutParams();
        params.width = width;
        params.height = height;
        gridView.setPadding(padding,padding,padding,padding);
        gridView.setLayoutParams(params);
        gridView.setHorizontalSpacing(padding);
        gridView.setVerticalSpacing(padding);
        gridView.setBackgroundResource(R.drawable.selector_white_bg);
        gridView.setBackgroundColor(UIUtils.getColor(R.color.grid_emoji_bg));
        gridView.setSelector(android.R.color.transparent);
        gridView.setNumColumns(7);
        EmojiAdapter adapter = new EmojiAdapter(mContext,emojiNames,padding,itemWidth);
        gridView.setAdapter(adapter);
        gridView.setOnItemClickListener(this);
        return gridView;
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Adapter adapter = parent.getAdapter();
        if (adapter instanceof EmojiAdapter) {
            EmojiAdapter emojiAdapter = (EmojiAdapter) adapter;
            //表情栏的item
            if (position < ((EmojiAdapter) parent.getAdapter()).getCount()-1) {
                //点击的是表情
                //先获取当前光标位置
                int curIndex = etContent.getSelectionStart();
                String emoji = emojiAdapter.getItem(position);
                StringBuilder sb = new StringBuilder(etContent.getText());
                sb.insert(curIndex,emoji);
                SpannableString spannableString = StringUtils.getContentText(mContext,etContent,sb.toString());
                etContent.setText(spannableString);
                //让光标到表情后
                etContent.setSelection(curIndex+emoji.length());
            } else {
                //点击的是回退
                etContent.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN,KeyEvent.KEYCODE_DEL));
            }
        }
    }
}
